<template>
	<view>
		<view class="return" @click="toReturn()" style="box-shadow: 1rpx 2rpx 4rpx 2rpx gainsboro;">
			<u-icon name="arrow-left" size="20"></u-icon>
		</view>
		<view class="weather-card">
			<!-- <image src="/static/bg3.png" class="bg"></image> -->
			<!-- 天气卡片内容 -->
			<view class="weather-container weather-loaded">
				<!-- 头部区域 -->
				<view class="weather-header">
					<view class="header-left">
						<span class="weather-tag">天气预报</span>
						<view class="location-info" @click="chooseCity">
							<u-icon name="map-fill" size="26" color="#01B192"></u-icon>
							<text class="location-text">高新区</text>
							<!-- <text class="location-text">{{ currentWeather.city }} {{ currentWeather.district }}</text> -->
							<!-- <u-icon name="arrow-right" size="20" color="#999" class="location-arrow"></u-icon> -->
						</view>
					</view>
					<view class="header-right">
						<view class="update-time">
							<text>更新于 {{ currentWeather.updateTime }}</text>
						</view>
						<!-- 刷新图标 -->
						<u-icon name="reload" size="28" color="#01B192" class="refresh-icon" @click="refreshWeather"
							:class="{ 'refreshing': isRefreshing }"></u-icon>
					</view>
				</view>

				<!-- 实时天气主体 -->
				<view class="current-weather">
					<view class="current-main">
						<view class="temp-container">
							<text class="current-temp">{{ currentWeather.temperature }}°</text>
							<text class="temp-unit">C</text>
						</view>
						<view class="weather-status">
							<text class="weather-text">{{ currentWeather.weather }}</text>
							<view class="weather-icon">
								<image :src="getWeatherIcon(currentWeather.weather)" mode="widthFix"></image>
							</view>
						</view>
					</view>

					<!-- 天气详情指标 -->
					<view class="weather-metrics">
						<view class="metric-item">
							<text class="metric-value">{{ currentWeather.windDirection }}</text>
							<text class="metric-label">风向</text>
							<image class="forecast-icon" src="/static/images/fx.png">
						</view>
						<view class="metric-item">
							<text class="metric-value">{{ currentWeather.windPower }}</text>
							<text class="metric-label">风力</text>
							<image class="forecast-icon" src="/static/images/fl.png">
						</view>
						<view class="metric-item">
							<text class="metric-value">{{ currentWeather.humidity }}%</text>
							<text class="metric-label">湿度</text>
							<image class="forecast-icon" src="/static/images/sd.png">
						</view>
					</view>
				</view>

				<!-- 未来预报 -->
				<view class="forecast-section">
					<text class="section-title">未来预报</text>
					<view class="forecast-slider">
						<view class="forecast-item" v-for="(day, index) in futureForecast" :key="index"
							:class="{ 'today': index === 0 }">
							<text class="forecast-date">{{ formatDate(day.date) }}</text>
							<text class="forecast-week">{{ day.week }}</text>
							<image :src="getWeatherIcon(day.day.weather)" mode="widthFix" class="forecast-icon"></image>
							<text class="forecast-weather">{{ day.day.weather }}</text>
							<text class="forecast-temp">{{ day.day.temperature }}°</text>
						</view>
					</view>
				</view>
			</view>

			<u-toast ref="uToast" />
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				apiKey: 'F2GBZ-2II6X-EQB4R-7MYZJ-K3S3E-KKBNB',
				defaultAdcode: '320300',
				// 天气数据
				currentWeather: {
					city: '加载中',
					district: '',
					temperature: '--',
					weather: '',
					windDirection: '--',
					windPower: '--',
					humidity: '--',
					updateTime: ''
				},
				futureForecast: [],
				// 状态变量
				loading: false,
				weatherLoaded: false,
				errorMsg: '',
				isLocating: false, // 定位状态
				isRefreshing: false, // 刷新状态
				ws: null,
				path: '/pages/weather/weather'
			};
		},
		mounted() {
			this.getWeatherData()
			// this.getHours()
		},
		onShow() {
			this.connectWebSocket()
		},
		onHide() {
			// 页面隐藏/切入后台时触发
			let that = this
			that.sendData({
				type: 'page_leave',
				path: that.path,
				params: ""
			});
		},
		onUnload() {
			// 页面卸载时触发
			let that = this
			that.sendData({
				type: 'page_leave',
				path: that.path,
				params: ""
			});
		},
		methods: {
			// 连接
			connectWebSocket() {
				let that = this
				const wsUrl = "wss://gxtravel.ncscloudmedia.com/wss"; // 确保使用wss（WebSocket Secure）如果服务器支持
				that.ws = new WebSocket(wsUrl);
				that.ws.onopen = () => {
					//console.log("连接已建立");
					// 这里可以发送初始化消息等
					that.sendData({
						type: 'page_enter',
						path: that.path,
						params: ""
					});
				};
				that.ws.onmessage = (event) => {
					console.log("Message from server ", event.data);
					// 处理接收到的消息
				};
				that.ws.onerror = (error) => {
					console.error("连接失败: ", error);
				};
				that.ws.onclose = () => {
					console.log("连接失败，重新连接");
					// 可以在这里尝试重新连接
					that.connectWebSocket();
				};
			},
			// 发送
			sendData(data) {
				if (this.ws && this.ws.readyState === WebSocket.OPEN) {
					// this.ws.send(data); // 确保发送JSON格式的数据
					this.ws.send(JSON.stringify(data)); // 确保发送JSON格式的数据
				} else {
					console.error("WebSocket is not open");
				}
			},
			getHours() {
				let that = this
				uni.request({
					url: 'https://api.openweathermap.org/data/2.5/forecast',
					method: 'GET',
					data: {
						appid: "11bd51d03928302a52975341b2f210c9",
						q: 'nanchang',
						output: 'jsonp',
						lan: 'en',
						units: 'metric' // 实时天气
					},
					success(res) {
						// console.log(res)
						let list = res.data
						// console.log(that.processWeatherData(list))
					},
					fail(res) {
						console.log(res)
					}
				})
			},
			processWeatherData(data) {
				const hourlyData = data.list.filter(item => item.dt_txt.includes(':00:00')); // 过滤出每小时的数据点
				return hourlyData;
			},
			/**
			 * 组件初始化方法，供页面调用
			 * 页面可以在需要的时候调用此方法初始化或重新加载天气数据
			 */
			initWeather() {
				// 重置状态
				this.errorMsg = '';
				this.weatherLoaded = false;

				// 开始定位并获取天气
				this.getWeatherData();
			},

			/**
			 * 刷新天气数据（只刷新天气，不重新定位）
			 */
			refreshWeather() {
				if (this.isRefreshing) return;

				this.isRefreshing = true;
				// this.$refs.uToast.show({
				//   title: '正在刷新...',
				//   duration: 800
				// });
				this.getWeatherData(2)
				// this.getWeatherData().then(() => {
				//   this.isRefreshing = false;
				//   this.$refs.uToast.show({
				//     title: '刷新成功',
				//     duration: 1000
				//   });
				// }).catch(() => {
				//   this.isRefreshing = false;
				//   this.$refs.uToast.show({
				//     title: '刷新失败',
				//     duration: 1000,
				//     type: 'error'
				//   });
				// });
			},

			/**
			 * 获取用户位置（经纬度）
			 */
			getUserLocation() {
				this.isLocating = true;

				// 使用uni-app的定位API获取经纬度
				uni.getLocation({
					type: 'gcj02', // 腾讯地图使用gcj02坐标系
					geocode: false,
					success: (res) => {
						this.isLocating = false;
						// 调用逆地址解析获取adcode
						this.getAdcodeByLocation(res.longitude, res.latitude);
					},
					fail: (err) => {
						this.isLocating = false;
						console.error('获取位置失败：', err);

						// 根据错误码给出具体提示
						let errMsg = '获取位置失败，请允许定位权限';
						if (err.errCode === 1) {
							errMsg = '请在设置中开启位置权限';
						} else if (err.errCode === 2) {
							errMsg = '位置服务不可用，请检查设备设置';
						} else if (err.errCode === 3) {
							errMsg = '定位超时，请稍后重试';
						}

						this.errorMsg = errMsg;

						// 定位失败时使用默认城市
						setTimeout(() => {
							this.getWeatherData();
						}, 1500);
					}
				});
			},

			/**
			 * 通过经纬度获取行政区划代码（adcode）
			 */
			getAdcodeByLocation(lng, lat) {
				this.loading = true;

				uni.request({
					url: 'https://apis.map.qq.com/ws/geocoder/v1/',
					method: 'GET',
					data: {
						key: this.apiKey,
						location: `${lat},${lng}`, // 纬度在前，经度在后
						get_poi: 0
					},
					success: (res) => {
						if (res.data.status === 0 && res.data.result.ad_info) {
							// 获取到adcode后更新并获取天气
							this.adcode = res.data.result.ad_info.adcode;
							this.getWeatherData();
						} else {
							this.loading = false;
							this.errorMsg = '解析位置信息失败，使用默认城市';
							// 解析失败使用默认城市
							setTimeout(() => {
								this.getWeatherData();
							}, 1500);
						}
					},
					fail: (err) => {
						this.loading = false;
						this.errorMsg = '位置解析请求失败，使用默认城市';
						console.error('解析位置失败：', err);
						// 请求失败使用默认城市
						setTimeout(() => {
							this.getWeatherData();
						}, 1500);
					}
				});
			},

			/**
			 * 获取天气数据（实时+未来预报）
			 */
			getWeatherData(n) {
				let that = this
				that.$jsonp('https://apis.map.qq.com/ws/weather/v1/', {
					key: "F2GBZ-2II6X-EQB4R-7MYZJ-K3S3E-KKBNB",
					location: '28.694426,115.975846',
					output: 'jsonp',
					type: 'now' // 实时天气
				}).then(res => {
					const realtimeData = res;
					// console.log(res)
					if (realtimeData.status === 0 && realtimeData.result.realtime) {
						if (n == 2) {
							this.isRefreshing = false;
							uni.showToast({
								title: '刷新成功'
							})
						}

						const realtime = realtimeData.result.realtime[0];
						// 处理实时天气数据
						this.currentWeather = {
							province: realtime.province,
							city: realtime.city,
							district: realtime.district,
							weather: realtime.infos.weather,
							temperature: realtime.infos.temperature,
							windDirection: realtime.infos.wind_direction,
							windPower: realtime.infos.wind_power,
							humidity: realtime.infos.humidity,
							updateTime: this.formatTime(realtime.update_time)
						};
						// 2. 获取未来预报
						this.getFutureWeather();
					} else {
						if (n == 2) {
							this.isRefreshing = false;
							uni.showToast({
								title: '刷新失败',
								icon: 'error'
							})
						}
						this.errorMsg = realtimeData.message || '获取实时天气失败';
						this.loading = false;
						this.weatherLoaded = false;
					}
				}).catch(err => {
					console.log(err);
				});
			},

			/**
			 * 获取未来天气预报
			 */
			getFutureWeather() {
				let that = this
				that.$jsonp('https://apis.map.qq.com/ws/weather/v1/', {
					key: "F2GBZ-2II6X-EQB4R-7MYZJ-K3S3E-KKBNB",
					location: '28.694426,115.975846',
					output: 'jsonp',
					type: 'future', // 未来预报
					get_md: 0 // 当天+未来3天
				}).then(res => {
					// console.log(res)
					const futureData = res;
					if (futureData.status === 0 && futureData.result.forecast) {
						this.futureForecast = futureData.result.forecast[0].infos;
						this.weatherLoaded = true;
					} else {
						this.errorMsg = futureData.message || '获取未来天气失败';
					}
				}).catch(err => {
					console.log(err);
				});
			},
			toReturn() {
				uni.navigateBack()
			},
			/**
			 * 根据天气状态获取对应图标
			 */
			getWeatherIcon(weather) {
				const weatherMap = {
					'晴天': '/static/images/icon5.png',
					'多云': '/static/images/icon3.png',
					'阴': '/static/images/icon9.png',
					'阵雨': '/static/images/icon2.png',
					'雨': '/static/images/icon2.png',
					'雷阵雨': '/static/images/icon12.png',
					'小雨': '/static/images/icon8.png',
					'中雨': '/static/images/icon2.png',
					'大雨': '/static/images/icon15.png',
					'暴雨': '/static/images/icon15.png',
					'大暴雨': '/static/images/icon15.png',
					'阵雪': '/static/images/icon7.png',
					'雪': '/static/images/icon7.png',
					'小雪': '/static/images/icon7.png',
					'中雪': '/static/images/icon1.png',
					'大雪': '/static/images/icon1.png',
					'暴雪': '/static/images/icon1.png',
					'雾': '/static/images/icon6.png',
					'冻雨': '/static/images/icon2.png',
					'沙尘暴': '/static/images/icon6.png',
					'小到中雨': '/static/images/icon2.png',
					'中到大雨': '/static/images/icon2.png',
					'大到暴雨': '/static/images/icon2.png',
					'暴雨到大暴雨': '/static/images/icon2.png',
					'大暴雨到特大暴雨': '/static/images/icon2.png',
					'小到中雪': '/static/images/icon1.png',
					'中到大雪': '/static/images/icon1.png',
					'大到暴雪': '/static/images/icon1.png',
					'浮尘': '/static/images/icon6.png',
					'扬沙': '/static/images/icon6.png',
					'强沙尘暴': '/static/images/icon6.png',
					'浓雾': '/static/images/icon6.png'
				};
				return weatherMap[weather] || '/static/images/qt.png';
			},

			/**
			 * 格式化时间
			 */
			formatTime(timeStr) {
				if (!timeStr) return '';
				return timeStr.split(' ')[1].slice(0, 5);
			},

			/**
			 * 格式化日期
			 */
			formatDate(dateStr) {
				if (!dateStr) return '';
				return dateStr.split('-').slice(1).join('-');
			},

			/**
			 * 城市选择功能
			 */
			chooseCity() {
				// this.$refs.uToast.show({
				//   title: '城市选择功能待开发'
				// });
			}
		}
	};
</script>

<style lang="scss" scoped>
	page {
		background: linear-gradient(90deg, #D5F6EB 0%, #EDFCFC 100%);
		// background: linear-gradient(to bottom,#EDFFF9,#D5F6EB);
	}

	.bg {
		position: fixed;
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
		z-index: -1;
	}

	/* 样式与之前版本保持一致 */
	.weather-card {
		width: 92%;
		margin: 24rpx auto;
		border-radius: 24rpx;
		overflow: hidden;
		position: relative;
		top: 100rpx;
	}

	.weather-container {
		background: rgba(255, 255, 255, 0.8);
		border-radius: 24rpx;
		box-shadow: 1rpx 2rpx 5rpx 2rpx gray;
		padding: 28rpx;
		// transform: translateY(20rpx);
		// transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
		// box-sizing: border-box;
	}

	.weather-loaded {
		opacity: 1;
		transform: translateY(0);
	}

	.weather-header {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 30rpx;
	}

	.header-left {
		display: flex;
		flex-direction: column;
		gap: 10rpx;
	}

	.header-right {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		gap: 8rpx;
	}

	.weather-tag {
		display: inline-block;
		padding: 6rpx 16rpx;
		background: linear-gradient(90deg, #01B192 0%, #00dfb6 100%);
		color: white;
		font-size: 30rpx;
		border-radius: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(64, 158, 255, 0.3);
	}

	.location-info {
		display: flex;
		align-items: center;
		gap: 10rpx;
		padding: 8rpx 0;
		cursor: pointer;
	}

	.location-text {
		font-size: 28rpx;
		color: #303133;
		font-weight: 500;
	}

	.location-arrow {
		opacity: 0.7;
		transition: transform 0.3s;
	}

	.location-info:hover .location-arrow {
		transform: translateX(5rpx);
	}

	.update-time {
		font-size: 22rpx;
		color: #909399;
		padding-top: 12rpx;
	}

	.refresh-icon {
		cursor: pointer;
		transition: transform 0.3s ease;
		margin-top: 5rpx;
	}

	.refresh-icon:hover {
		transform: rotate(30deg);
	}

	.refreshing {
		animation: spin 1s linear infinite;
	}

	.current-weather {
		display: flex;
		flex-direction: column;
		gap: 30rpx;
		margin-bottom: 20rpx;
	}

	.current-main {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10rpx 0;
	}

	.temp-container {
		display: flex;
		align-items: baseline;
		gap: 10rpx;
	}

	.current-temp {
		font-size: 80rpx;
		font-weight: 700;
		color: #303133;
		line-height: 1;
		background: linear-gradient(90deg, #303133 0%, #606266 100%);
		-webkit-background-clip: text;
		background-clip: text;
		color: transparent;
	}

	.temp-unit {
		font-size: 32rpx;
		color: #606266;
		margin-bottom: 10rpx;
	}

	.weather-status {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.weather-text {
		font-size: 36rpx;
		color: #303133;
		font-weight: 500;
	}

	.weather-icon image {
		width: 100rpx;
		height: 100rpx;
		filter: drop-shadow(0 5rpx 10rpx rgba(0, 0, 0, 0.1));
	}

	.weather-metrics {
		display: flex;
		justify-content: space-around;
		padding: 20rpx 0;
		background: rgba(255, 255, 255, 0.7);
		border-radius: 16rpx;
		backdrop-filter: blur(10rpx);
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.metric-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 8rpx;
		padding: 0 10rpx;
	}

	.metric-value {
		font-size: 28rpx;
		color: #303133;
		font-weight: 500;
	}

	.metric-label {
		font-size: 26rpx;
		color: #909399;
	}

	.forecast-section {
		margin-top: 10rpx;
	}

	.section-title {
		display: block;
		font-size: 28rpx;
		color: #606266;
		margin-bottom: 20rpx;
		padding-left: 8rpx;
		font-weight: 500;
	}

	.forecast-slider {
		display: flex;
		gap: 16rpx;
		overflow-x: auto;
		padding-bottom: 10rpx;
		scrollbar-width: none;

		&::-webkit-scrollbar {
			display: none;
		}
	}

	.forecast-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		min-width: 140rpx;
		padding: 20rpx 10rpx;
		background: rgba(255, 255, 255, 0.6);
		border-radius: 16rpx;
		backdrop-filter: blur(8rpx);
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		transition: transform 0.3s, box-shadow 0.3s;
	}

	.forecast-item:hover {
		transform: translateY(-5rpx);
		box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.08);
	}

	.forecast-item.today {
		background: linear-gradient(135deg, #D5F6EB 0%, #EDFCFC 100%);
		border: 1rpx solid #00BB9B;
	}

	.forecast-date {
		font-size: 28rpx;
		color: #303133;
		font-weight: 500;
		margin-bottom: 6rpx;
	}

	.forecast-week {
		font-size: 26rpx;
		color: #909399;
		margin-bottom: 15rpx;
	}

	.forecast-icon {
		width: 60rpx;
		height: 60rpx;
		margin-bottom: 15rpx;
	}

	.forecast-weather {
		font-size: 30rpx;
		color: #303133;
		margin-bottom: 10rpx;
		text-align: center;
		min-height: 30rpx;
	}

	.forecast-temp {
		font-size: 28rpx;
		color: #01B192;
		font-weight: 500;
	}

	.loading-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 80rpx 0;
		background: white;
		border-radius: 24rpx;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
	}

	.loading-spinner {
		animation: spin 1.5s linear infinite;
	}

	.loading-text {
		margin-top: 20rpx;
		font-size: 28rpx;
		color: #606266;
	}

	.error-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 60rpx 30rpx;
		background: white;
		border-radius: 24rpx;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
		text-align: center;
	}

	.error-text {
		margin: 20rpx 0;
		font-size: 28rpx;
		color: #f56c6c;
		max-width: 80%;
	}

	.retry-btn {
		display: flex;
		align-items: center;
		gap: 10rpx;
		padding: 14rpx 30rpx;
		background: linear-gradient(90deg, #01B192 0%, #01B192 100%);
		color: white;
		font-size: 28rpx;
		border-radius: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(64, 158, 255, 0.3);
		border: none;
		margin-top: 10rpx;
		transition: transform 0.2s;
	}

	.retry-btn:active {
		transform: scale(0.95);
	}

	@keyframes spin {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}
</style>